#!/bin/bash
set -e
set -o pipefail


############################## 基础通用函数 ##############################
# 打印
comm_print_note(){
    local msg=$1
    echo -e "$(date +"%Y-%m-%d %H:%M:%S") \033[32m[Note]\033[0m ${msg} "
}

comm_print_warning(){
    local msg=$1
    echo -e "$(date +"%Y-%m-%d %H:%M:%S") \033[33m[Warning]\033[0m ${msg}"
}

comm_print_error(){
    local msg=$1
    echo -e "$(date +"%Y-%m-%d %H:%M:%S") \033[31m[Error]\033[0m ${msg}"
}


# # 挂载本地yum源
# function comm_mount_local(){
#   local_yum_file=$1
#   if [ ! -d /tmp/local_yum ];then
#     tar zxf ${local_yum_file}
#     mv ${local_yum_file}/local_yum /tmp/

#     cat > /etc/yum.repos.d/local_yum.repo <<EOF
# [local]
# name=pglocal_yum
# baseurl=file:///tmp/local_yum
# gpgcheck=0
# enabled=1
# EOF
#   fi
# }

################################# 系统初始化设置 #####################################
# 关闭 selinux
function comm_system_disabe_selinux(){
    set +e
    setenforce 0
    set -e
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
    systemctl disable firewalld.service
    systemctl stop firewalld.service
}

# 关闭防火墙
function comm_do_stop_firewalld(){
  systemctl stop firewalld
  systemctl disable firewalld
}


# 优化设置资源限制
function comm_init_system_limits(){
  local check_value=$(cat /etc/security/limits.conf|grep "* soft nproc 65535"|wc -l)
  if [ $check_value -eq 0 ];then
    cat >> /etc/security/limits.conf <<EOF
* soft nproc 65535
* hard nproc 65535
root soft nofile 65535
root hard nofile 65535
* soft nofile 65535
* hard nofile 65535
EOF
  fi

ulimit -n 65536
ulimit -u 65536
}

# 优化内核参数
function comm_optimize_system_kernel_parameters() {
    local check_value=$(cat /etc/sysctl.conf|grep "net.ipv4.tcp_max_syn_backlog = 65535"|wc -l)
    if [ $check_value -eq 0 ];then
      local timestamp=`date +%F-%T`
      mv /etc/sysctl.conf /etc/sysctl.conf.bak-$timestamp
      cat >> /etc/sysctl.conf << EOF
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_max_tw_buckets = 55000
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1100 65535
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 200000
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
# 路由转发
net.ipv4.ip_forward = 1
# 开启反向路径过滤
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.lo.arp_announce=2
net.ipv4.conf.all.arp_announce=2
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syncookies = 1
vm.swappiness = 2
kernel.sysrq = 1
vm.max_map_count = 262144
fs.inotify.max_user_instances = 8192
#net.netfilter.nf_conntrack_max = 524288
EOF
      # 立即生效
      sysctl -p

      echo "DefaultLimitNOFILE=65535" >> /etc/systemd/system.conf
      systemctl daemon-reload
    fi
}

# 关闭透明大页
function comm_disable_transparent_hugepage(){
    if test -f /sys/kernel/mm/transparent_hugepage/enabled; then                
    echo never > /sys/kernel/mm/transparent_hugepage/enabled                
    fi
}


# 时间同步
function comm_ntpd(){
    if [ $sys_type = "yum" ];then
      yum install -y ntp
    else
      apt install ntp -y
    fi
    NTP_SERVER="ntp2.tencent.com"
    sudo sed -i "s/^server .*$/server ${NTP_SERVER} iburst/g" /etc/ntp.conf
    systemctl enable ntpd
    systemctl start ntpd
    ntpdate -u ${NTP_SERVER}
    hwclock -w
}

# 检查端口是否被占用
function comm_check_port_occupied(){
  local port=$1
  local check_value=$(ss -ntpl | grep -w ${port}|wc -l)
  if [ $check_value -gt 0 ];then
    comm_print_error "端口 [$port] 已被占用."
    exit 1
  fi
}

# 检查是否可以上网
function comm_check_connect_internet(){
    local ret_code=$(curl -I -s --connect-timeout 1 www.baidu.com -w %{http_code}|tail -n1)
    if [ "x$ret_code" = "x200" ];then
        return 0
    else
        return 1
    fi
}

# 判断用户是否存在
## 传入：用户
function comm_is_user_exists(){
   local user=$1
   local check_value=$(cat /etc/passwd|grep ${user}|wc -l)
   if [ $check_value -eq 0 ];then
     return 0
   else
     return 1
   fi
}


# 检测目录是否为空，不为空则抛出异常
function comm_is_dir_empty(){
  local dir=$1
  if [ ! -d "$dir" ];then
    return 0
  fi
  dir_contents=$(ls -A "$dir")
  if [ -z "$dir_contents" ];then
     return 0
  else
    comm_print_error "目录 $dir 不为空！"
    exit 1
  fi
}
